#include"skillWidget.h"

SkillWidget::SkillWidget(QWidget* p):QWidget(p),ui(new Ui::SkillWidget),filePath("")
{
    ui->setupUi(this);
    setInputMask();

    connect(ui->treeWidget_skillCondition,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(s_skillConditionItemDoubleClicked(QTreeWidgetItem*,int)));
    connect(ui->tableWidget_skill_condtion,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(s_cellDoubleClicked(int,int)));
}

SkillWidget::~SkillWidget()
{
    delete ui;
}

void SkillWidget::setInputMask()
{
    QIntValidator* charValidator = new QIntValidator(-128,127,this);

    ui->lineEdit_skill_attackAddon->setValidator(charValidator);
    ui->lineEdit_skill_defenseAddon->setValidator(charValidator);
    ui->lineEdit_skill_strengthAddon->setValidator(charValidator);
    ui->lineEdit_skill_goodAddon->setValidator(charValidator);
    ui->lineEdit_skill_badAddon->setValidator(charValidator);
}

Skill SkillWidget::getSkillFromUI()
{
    Skill s;
    s.id = (qint32)ui->lineEdit_skill_id->text().toInt();
    s.description = ui->plainTextEdit_skill_description->toPlainText();
    s.attack_addon = (qint8)ui->lineEdit_skill_attackAddon->text().toInt();
    s.defense_addon = (qint8)ui->lineEdit_skill_defenseAddon->text().toInt();
    s.strength_addon = (qint8)ui->lineEdit_skill_strengthAddon->text().toInt();
    s.country = (qint8)ui->comboBox_skil_good->currentIndex();
    s.country_addon = (qint8)ui->lineEdit_skill_goodAddon->text().toInt();
    s.opponent = (qint8)ui->comboBox_skill_bad->currentIndex();
    s.opponent_addon = (qint8)ui->lineEdit_skill_badAddon->text().toInt();

    int cnt = 0;
    while(ui->tableWidget_skill_condtion->item(cnt,1))
    {
        if(ui->tableWidget_skill_condtion->item(cnt,1)->text().replace(" ","").isEmpty())
            break;
        cnt++;
    }
    s.skill_condition_count = (qint32)cnt;
    if(cnt>0)
    {
        s.condition = new SkillCondition[cnt];
        for(int i=0;i<cnt;i++)
        {
            if(ui->tableWidget_skill_condtion->item(i,1))
                s.condition[i].id = (qint32) ui->tableWidget_skill_condtion->item(i,1)->text().toInt();
            else
                s.condition[i].id = 0;
            if(ui->tableWidget_skill_condtion->item(i,2))
                s.condition[i].type = (qint8) ui->tableWidget_skill_condtion->item(i,2)->text().toInt();
            else
                s.condition[i].type = 0;
        }
    }else
        s.condition = 0;
    return s;
}

void SkillWidget::displaySkillToUI(Skill& s)
{
    clearUI();

    ui->lineEdit_skill_id->setText(QString::number(s.id));
    ui->plainTextEdit_skill_description->setPlainText(s.description);
    ui->lineEdit_skill_attackAddon->setText(QString::number(s.attack_addon));
    ui->lineEdit_skill_defenseAddon->setText(QString::number(s.defense_addon));
    ui->lineEdit_skill_strengthAddon->setText(QString::number(s.strength_addon));
    ui->comboBox_skil_good->setCurrentIndex(s.country);
    ui->lineEdit_skill_goodAddon->setText(QString::number(s.country_addon));
    ui->comboBox_skill_bad->setCurrentIndex(s.opponent);
    ui->lineEdit_skill_badAddon->setText(QString::number(s.opponent_addon));

    int cnt = (int)s.skill_condition_count;
    for(int i=0;i<cnt;i++)
    {
        ui->tableWidget_skill_condtion->setItem(i,1,new QTableWidgetItem(QString::number(s.condition[i].id)));
        ui->tableWidget_skill_condtion->setItem(i,2,new QTableWidgetItem(QString::number(s.condition[i].type)));
        QString condition_str;
        if(s.condition[i].type==EQUIP_IDX)
            condition_str = QString(equipMap.value((int)s.condition[i].id));
        if(s.condition[i].type==GENERAL_IDX)
            condition_str = QString(generalMap.value((int)s.condition[i].id));
        ui->tableWidget_skill_condtion->setItem(cnt,0,new QTableWidgetItem(condition_str));
    }
}

Skill SkillWidget::readSkillFromFile()
{
    Skill s;
    QFile f(filePath);
    if(f.exists())
    {
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>s;
        f.close();
        displaySkillToUI(s);
    }else
        WARNING_FILE_NOT_EXIST;
    return s;
}

bool SkillWidget::saveSkillToFile()
{
    if(filePath.isEmpty())
    {
        WARNING_NO_NAME;
        return false;
    }else
    {
        Skill s = getSkillFromUI();
        QFile f(filePath);
        f.open(QIODevice::WriteOnly);
        QDataStream out(&f);
        out<<s;
        f.close();
        return true;
    }
}

void SkillWidget::clearUI()
{
    ui->lineEdit_skill_id->clear();
    ui->plainTextEdit_skill_description->clear();
    ui->lineEdit_skill_attackAddon->clear();
    ui->lineEdit_skill_defenseAddon->clear();
    ui->lineEdit_skill_strengthAddon->clear();
    ui->lineEdit_skill_goodAddon->clear();
    ui->lineEdit_skill_badAddon->clear();

    for(int i=0;i<ui->tableWidget_skill_condtion->rowCount();i++)
    {
        for(int j=0;j<ui->tableWidget_skill_condtion->columnCount();j++)
        {
            if(ui->tableWidget_skill_condtion->item(i,j))
                delete (ui->tableWidget_skill_condtion->item(i,j));
        }
    }
}

void SkillWidget::exportToBinary(QString workspacepath)
{
    //export skill
    QFile f4(workspacepath+"/"+SKILL_EXPORT_NAME);
    f4.open(QIODevice::WriteOnly);
    QDataStream out4(&f4);

    out4<<Skill::magic;
    out4<<Skill::version;

    QDir dir_skill(workspacepath+"/"+SKILL_STR);
    QString mfilter = QString("*")+QString(SKILL_FILE_SUFFIX);
    QStringList skillList = dir_skill.entryList(QStringList(mfilter));
    for(int i=0;i<skillList.length();i++)
    {
        Skill s;
        QFile f41(dir_skill.absolutePath()+"/"+skillList.at(i));
        f41.open(QIODevice::ReadOnly);
        QDataStream in(&f41);
        in>>s;
        out4<<s;
        f41.close();
    }

    f4.close();
}

void SkillWidget::exportToXML(QString workspacepath)
{
    //*****write XML*******//
    QFile file(workspacepath+"/output/skill.xml");
    file.open(QIODevice::WriteOnly);
    QDomDocument doc;
    QDomText text;
    QDomProcessingInstruction instruction;
    instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"gb18030\"");
    doc.appendChild(instruction);
    QDomElement root=doc.createElement("root");
    doc.appendChild(root);

    QDir dir_skill(workspacepath+"/"+SKILL_STR);
    QStringList skillList = dir_skill.entryList(QStringList()<<(QString("*")+SKILL_FILE_SUFFIX));
    int cnt = skillList.length();
    for(int i=0;i<cnt;i++)
    {

        QDomElement skill=doc.createElement("skill");
        root.appendChild(skill);

        Skill e;
        QFile mf(dir_skill.absolutePath()+"/"+skillList.at(i));
        mf.open(QIODevice::ReadOnly);
        QDataStream in(&mf);
        in>>e;
        mf.close();

        QDomElement element;

        element=doc.createElement("id");
        text=doc.createTextNode(QString::number(e.id));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("description");
        text=doc.createTextNode(e.description);
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("attack_addon");
        text=doc.createTextNode(QString::number(e.attack_addon));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("defense_addon");
        text=doc.createTextNode(QString::number(e.defense_addon));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("strength_addon");
        text=doc.createTextNode(QString::number(e.strength_addon));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("country");
        text=doc.createTextNode(QString::number(e.country));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("country_addon");
        text=doc.createTextNode(QString::number(e.country_addon));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("opponent");
        text=doc.createTextNode(QString::number(e.opponent));
        element.appendChild(text);
        skill.appendChild(element);

        element=doc.createElement("opponent_addon");
        text=doc.createTextNode(QString::number(e.opponent_addon));
        element.appendChild(text);
        skill.appendChild(element);

        for(int l=0;l<e.skill_condition_count;l++)
        {
            QDomElement conditionElement=doc.createElement("condition");
            skill.appendChild(conditionElement);

            QDomElement tmp;
            tmp=doc.createElement("id");
            text=doc.createTextNode(QString::number(e.condition[l].id));
            tmp.appendChild(text);
            conditionElement.appendChild(tmp);

            tmp=doc.createElement("type");
            text=doc.createTextNode(QString::number(e.condition[l].type));
            tmp.appendChild(text);
            conditionElement.appendChild(tmp);
        }
    }

    QTextStream out(&file);
    doc.save(out,4);
    file.close();
}

bool SkillWidget::importFromXML(QString workspacepath,QString xmlFile)
{
    QFile f(xmlFile);
    f.open(QIODevice::ReadOnly|QIODevice::Text);

    QDomDocument docment;

    if(!docment.setContent(&f,false))
    {
        return false;
    }

    QDir dir_root(workspacepath+"/"+SKILL_STR);
    QDomElement root = docment.documentElement();

    QDomNodeList skillChildren = root.childNodes();
    if(root.elementsByTagName("skill").length()==0)
        return false;
    for(int i=0;i<skillChildren.length();i++)
    {

        QDomNodeList skillAtr = skillChildren.at(i).toElement().childNodes();

        Skill s;

        s.id = (qint32)skillAtr.at(0).toElement().text().toInt();
        s.description = skillAtr.at(1).toElement().text();
        s.attack_addon = (qint8)skillAtr.at(2).toElement().text().toInt();
        s.defense_addon = (qint8)skillAtr.at(3).toElement().text().toInt();
        s.strength_addon = (qint8)skillAtr.at(4).toElement().text().toInt();
        s.country = (qint8)skillAtr.at(5).toElement().text().toInt();
        s.country_addon = (qint8)skillAtr.at(6).toElement().text().toInt();
        s.opponent = (qint8)skillAtr.at(7).toElement().text().toInt();
        s.opponent_addon = (qint8)skillAtr.at(8).toElement().text().toInt();

        QDomNodeList conditionList = skillChildren.at(i).toElement().elementsByTagName("condition");
        if(conditionList.length()>0)
        {
            s.skill_condition_count=conditionList.length();
            s.condition = new SkillCondition[s.skill_condition_count];
            for(int j=0;j<s.skill_condition_count;j++)
            {
                QDomNodeList tempList = conditionList.at(j).toElement().childNodes();
                s.condition[j].id = (qint32) tempList.at(0).toElement().text().toInt();
                s.condition[j].type = (qint8) tempList.at(1).toElement().text().toInt();
            }
        }

        QString skillName = QString::number(s.id)+QString(SKILL_FILE_SUFFIX);

        QFile mf(dir_root.absolutePath()+"/"+skillName);
        mf.open(QIODevice::WriteOnly);
        QDataStream out(&mf);
        out<<s;
        mf.close();
    }

    return true;
}

void SkillWidget::addTreeItems(QList<QTreeWidgetItem*> items)
{
    //    ui->treeWidget_mission_item->invisibleRootItem()->
    for(int i=0;i<ui->treeWidget_skillCondition->invisibleRootItem()->childCount();i++)
    {
        QTreeWidgetItem* tmp = ui->treeWidget_skillCondition->invisibleRootItem()->child(i);
        ui->treeWidget_skillCondition->invisibleRootItem()->removeChild(tmp);
        delete tmp;
    }
    int cnt = items.length();
    for(int i=0;i<cnt;i++)
    {
        QTreeWidgetItem* tmp = items.at(i);
        ui->treeWidget_skillCondition->invisibleRootItem()->addChild(tmp->clone());
    }
}

void SkillWidget::initialMap()
{
    equipMap.clear();
    generalMap.clear();

    //initial equipMap
    QDir dir_weapon(workPath+"/"+EQUIP_STR+"/"+WEAPON_STR);
    QDir dir_armor(workPath+"/"+EQUIP_STR+"/"+ARMOR_STR);
    QDir dir_horse(workPath+"/"+EQUIP_STR+"/"+HORSE_STR);

    QString mfilter = QString("*")+QString(EQUIP_FILE_SUFFIX);
    QStringList weaponList = dir_weapon.entryList(QStringList()<<mfilter);
    QStringList armorList = dir_armor.entryList(QStringList()<<mfilter);
    QStringList horseList = dir_horse.entryList(QStringList()<<mfilter);

    Equipment e;

    for(int i=0;i<weaponList.length();i++)
    {
        QFile f(dir_weapon.absolutePath()+"/"+weaponList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>e;
        equipMap.insert((int)e.id,e.name);
        f.close();
    }

    for(int i=0;i<armorList.length();i++)
    {
        QFile f(dir_armor.absolutePath()+"/"+armorList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>e;
        equipMap.insert((int)e.id,e.name);
        f.close();
    }

    for(int i=0;i<horseList.length();i++)
    {
        QFile f(dir_horse.absolutePath()+"/"+horseList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>e;
        equipMap.insert((int)e.id,e.name);
        f.close();
    }
//    qDebug()<<weaponList;

    //initial generalMap
    QDir dir_five(workPath+"/"+GENERAL_STR+"/"+GENERAL_FIVE_STAR_STR);
    QDir dir_four(workPath+"/"+GENERAL_STR+"/"+GENERAL_FOUR_STAR_STR);
    QDir dir_three(workPath+"/"+GENERAL_STR+"/"+GENERAL_THREE_STAR_STR);
    QDir dir_two(workPath+"/"+GENERAL_STR+"/"+GENERAL_TWO_STAR_STR);
    QDir dir_one(workPath+"/"+GENERAL_STR+"/"+GENERAL_ONE_STAR_STR);

    mfilter = QString("*")+QString(GENERAL_FILE_SUFFIX);
    QStringList fiveList = dir_five.entryList(QStringList()<<mfilter);
    QStringList fourList = dir_four.entryList(QStringList()<<mfilter);
    QStringList threeList = dir_three.entryList(QStringList()<<mfilter);
    QStringList twoList = dir_two.entryList(QStringList()<<mfilter);
    QStringList oneList = dir_one.entryList(QStringList()<<mfilter);

    General g;

    for(int i=0;i<fiveList.length();i++)
    {
        QFile f(dir_five.absolutePath()+"/"+fiveList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>g;
        generalMap.insert((int)g.id,g.name);
        f.close();
    }

    for(int i=0;i<fourList.length();i++)
    {
        QFile f(dir_four.absolutePath()+"/"+fourList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>g;
        generalMap.insert((int)g.id,g.name);
        f.close();
    }

    for(int i=0;i<threeList.length();i++)
    {
        QFile f(dir_three.absolutePath()+"/"+threeList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>g;
        generalMap.insert((int)g.id,g.name);
        f.close();
    }

    for(int i=0;i<twoList.length();i++)
    {
        QFile f(dir_two.absolutePath()+"/"+twoList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>g;
        generalMap.insert((int)g.id,g.name);
        f.close();
    }

    for(int i=0;i<oneList.length();i++)
    {
        QFile f(dir_one.absolutePath()+"/"+oneList.at(i));
        f.open(QIODevice::ReadOnly);
        QDataStream in(&f);
        in>>g;
        generalMap.insert((int)g.id,g.name);
        f.close();
    }

//    qDebug()<<equipMap.values();
//    qDebug()<<generalMap.values();
}

//*************slot functions*************//
void SkillWidget::s_skillConditionItemDoubleClicked(QTreeWidgetItem *item, int col)
{
    int cnt = 0;
    while(ui->tableWidget_skill_condtion->item(cnt,0))
    {
        if(ui->tableWidget_skill_condtion->item(cnt,0)->text().replace(" ","").isEmpty())
            break;
        cnt++;
    }

    QString itemText = item->text(col);

    if(itemText.endsWith(QString(EQUIP_FILE_SUFFIX)))
    {
        QString name = item->text(col).replace(QString(EQUIP_FILE_SUFFIX),"");
        ui->tableWidget_skill_condtion->setItem(cnt,0,new QTableWidgetItem(name));
        ui->tableWidget_skill_condtion->setItem(cnt,1,new QTableWidgetItem(QString::number((int)equipMap.key(name))));
        ui->tableWidget_skill_condtion->setItem(cnt,2,new QTableWidgetItem(QString::number(EQUIP_IDX)));
    }
    if(itemText.endsWith(QString(GENERAL_FILE_SUFFIX)))
    {
        QString name = item->text(col).replace(QString(GENERAL_FILE_SUFFIX),"");
        ui->tableWidget_skill_condtion->setItem(cnt,0,new QTableWidgetItem(name));
        ui->tableWidget_skill_condtion->setItem(cnt,1,new QTableWidgetItem(QString::number((int)generalMap.key(name))));
        ui->tableWidget_skill_condtion->setItem(cnt,2,new QTableWidgetItem(QString::number(GENERAL_IDX)));
    }
}

void SkillWidget::s_cellDoubleClicked(int row, int column)
{
    if(column==0||column==1||column==2)
    {
        delete (ui->tableWidget_skill_condtion->takeItem(row,0));
        delete (ui->tableWidget_skill_condtion->takeItem(row,1));
        delete (ui->tableWidget_skill_condtion->takeItem(row,2));
    }
}
